import axios from 'axios'

const API_BASE_URL = 'http://localhost:8123/api'

export const apiService = {
  // 创建带有重连机制的SSE连接
  createEventSource(url, maxRetries = 3) {
    let retries = 0;
    let eventSource = null;
    
    const connect = () => {
      eventSource = new EventSource(url);
      
      eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error);
        
        // 关闭当前连接
        eventSource.close();
        
        // 尝试重连
        if (retries < maxRetries) {
          retries++;
          console.log(`尝试重连 (${retries}/${maxRetries})...`);
          setTimeout(connect, 2000); // 2秒后重连
        }
      };
      
      return eventSource;
    };
    
    return connect();
  },
  
  // 恋爱大师应用SSE聊天
  getLoveAppChatSSE(message, chatId) {
    const url = `${API_BASE_URL}/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`;
    return this.createEventSource(url);
  },

  // 超级智能体应用聊天
  getSuperAgentChatSSE(message) {
    const url = `${API_BASE_URL}/ai/manus/chat?message=${encodeURIComponent(message)}`;
    return this.createEventSource(url);
  }
} 